package com.wxtf.platform.plugins.dictionary;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: DictionaryAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.dictionary</li>
 * <li>Description: 系统字典</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on 2012-10-8 下午03:34:14</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class DictionaryAction extends LogicBase implements CommonsCallProvider {
	private static final Log log = LogFactory.getLog(DictionaryAction.class);

	public DictionaryAction(String jsonArray) {

	}

	@Override
	public Object run(){
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
			} else if("queryP".equals(this.getMethodName())) {
				msg = this.queryP(this.getLogicData());
			} else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {
				msg = this.update(this.getLogicData());
			} else if("delete".equals(this.getMethodName())) {
				msg = this.delete(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")) {
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	private String[] fields = {
			"tmgd_id","tmgd_type", "tmgd_description", "tmgd_code", "tmgd_name", "tmgd_order_num", "tmgd_is_valid", "tmgd_memo",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
	
	@Override
	public Object select(Object jsonArray) throws Exception {
		sql = "from tm_general_dictionary where 1 = 1";
		JSONArray array = JSONArray.fromObject(jsonArray);
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			String pid = jsonObject.getString("pid");
			sql += " and tmgd_type = '" + pid + "'";
			if("init".equals(types)) {// 初始查询
				
			} else if("serch1".equals(types)) {// 条件查询
				
				
			}
		}
		// 排序
		String sortname = this.getRequest().getParameter("sortname");
		String sortorder = this.getRequest().getParameter("sortorder");
		if(sortname != null && sortname != null) {
			sql += " order by " + sortname + " " + sortorder;
		} else {
			sql += " order by tmgd_type, tmgd_order_num";
		}
		String countSql = "select count(*) " + sql;
		String querySql = "select tmgd_id,tmgd_type,tmgd_description,tmgd_code,tmgd_name,tmgd_order_num,tmgd_is_valid,tmgd_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time " + sql;
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	/** 
	 * 描述：queryP 查询父字典项，即字典分类
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn 2012-10-8  下午04:27:53
	 * @author chun_chang
	 */
	public Object queryP(Object jsonArray) throws Exception {
		String countSql = "select count(distinct tmgd_type) from tm_general_dictionary";
		String querySql = "select distinct tmgd_type, tmgd_description from tm_general_dictionary order by tmgd_type";
		String[] fields = { "tmgd_type", "tmgd_description" };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String curTime = FormatUtil.getCurentDateTime();
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		obj[0] = AccessDataBaseUtil.getPKUUID();
		obj[obj.length - 4] = user.getUserId();
		obj[obj.length - 3] = curTime;
		obj[obj.length - 2] = user.getUserId();
		obj[obj.length - 1] = curTime;
		
		sql = "insert into tm_general_dictionary(tmgd_id,tmgd_type,tmgd_description,tmgd_code,tmgd_name,tmgd_order_num,tmgd_is_valid,tmgd_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		this.updUserDic();
		return "\"保存成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String curTime = FormatUtil.getCurentDateTime();
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[7];
		obj[0] = jsonObject.getString("tmgd_name");
		obj[1] = jsonObject.getString("tmgd_order_num");
		obj[2] = jsonObject.getString("tmgd_is_valid");
		obj[3] = jsonObject.getString("tmgd_memo");
		obj[4] = user.getUserId();
		obj[5] = curTime;
		obj[6] = jsonObject.getString("tmgd_id");
		
		sql = "update tm_general_dictionary set tmgd_name = ?,tmgd_order_num = ?,tmgd_is_valid=?,tmgd_memo=?,last_modify_by=?,last_modify_time=? where tmgd_id = ?";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		this.updUserDic();
		return "\"保存成功\"";
	}
	
	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		sql = "delete from tm_general_dictionary where tmgd_id = ?";
		
		AccessDataBaseUtil.deleteByIds(sql, ids);
		this.updUserDic();
		return "\"删除成功\"";
	}

	/** 
	 * 描述：updUserDic 更新用户字典
	 * @throws Exception
	 * @CreateOn 2012-10-9  上午10:35:59
	 * @author chun_chang
	 */
	private void updUserDic() throws Exception{
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		Map<String, List<Map<String, String>>> dicMap = user.getDicMap();
		sql = "select tmgd_type,tmgd_description,tmgd_id,tmgd_name from tm_general_dictionary where tmgd_is_valid = '1' order by tmgd_order_num";
		String[] jsonField1 = { "tmgd_type", "tmgd_description", "tmgd_id", "tmgd_name" };
		List<Map<String, String>> list5 = AccessDataBaseUtil.query(jsonField1, sql, null);
		for(Map<String, String> map: list5) {
			List<Map<String, String>> list6 = dicMap.get(map.get("tmgd_type"));//获取userBean中的字典类型
			if(null == list6) {
				list6 = new ArrayList<Map<String, String>>();
				dicMap.put(map.get("tmgd_type"), list6);
			}
			list6.add(map);
		}
	}
	
	@Override
	public Object setRequest(HttpServletRequest request) throws Exception{
		this.request = request;
		return request;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception{
		return null;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

}
